<?php
namespace Admin\Controller;

use Common\Lib\User\UserHelper;
use Common\Lib\User\UserInfoException;
use Think\Exception;

/**
 * 用户相关控制器
 * Class UserController
 * @package Admin\Controller
 */
class UserController extends AbstractController  {
    private $Sex;
    public function _initialize(){
        parent::_initialize();
        $this->Sex = array('1' => '男','2' => '女');
    }
    /**
     * 用户列表
     */
    public function index(){
        $keyword = I('keyword');
        if(!empty($keyword)){
            $where['u.UserNO|u.UserName|u.TrueName|u.Address|u.Phone|u.EMail|u.CardNO'] = array('like','%'.$keyword.'%');
        }
        $where['u.IsDel'] = array('neq','1');

        $count = M('User as u')->where($where)->count();
        $page = $this->page($count, 20);
        $fields = 'u.*,case u.Sex when \'1\' then \'男\' when \'2\' then \'女\' end as Sex';
        $list = M('User as u')
            ->where($where)->order('u.OrderNO desc,u.ID asc')->field($fields)->limit($page->firstRow . ',' . $page->listRows)->select();
        foreach($list as $key=>$user){
            $dep_rel = M('user_dep_rel')->where(array('UserID' => $user['ID']))->field('GROUP_CONCAT(DepID) as DepID')->find();
            if($dep_rel['DepID']){
                $departmentList = M('Department')->where(array('ID' => array('in',$dep_rel['DepID'])))->select();
                foreach($departmentList as $department){
                    $list[$key]['Department'] .= $department['Name'].'</br>';
                }
            }

        }

        $this->assign('list',$list);
        $this->assign("page", $page->show('Admin'));
        $this->display();
    }

    /**
     * 添加用户
     */
    public function add(){
        if(IS_POST){
            try{
                $data = $_POST;
                $result = UserHelper::add($data);
                if(!empty($_POST['RoleID']) && is_array($_POST['RoleID'])){
                    $RoleIDs = I('post.RoleID/a');
                    $role_user_model=M("Role_user_rel");
                    $role_user_model->where(array("UserID"=>$result))->delete();
                    foreach ($RoleIDs as $role_id){
                        $role_user_model->add(array("RoleID"=>$role_id,"UserID"=>$result));
                    }
                }
                if(!empty($_POST['ApplyUserID'])){
                    $departments = I('ApplyUserID');
                    $departmentList = explode(',',$departments);
                    foreach($departmentList as $item){
                        $UserDepData['UserID'] = $result;
                        $UserDepData['DepID'] =  $item;
                        $rel = M('User_dep_rel')->where($UserDepData)->find();
                        if(!$rel){
                            M('User_dep_rel')->add($UserDepData);
                        }
                    }
                }

                $this->success('添加成功！');
            }catch(Exception $exception){
                $this->error($exception->getMessage());
            }
        }else{
            $where['IsDel'] = array('neq','1');
            $Roles = M('Role')->where($where)->order('ID desc')->select();
            $this->assign('Roles',$Roles);
            $this->assign('Sex',$this->Sex);
            $this->display();
        }
    }

    /**
     * 编辑用户
     */
    public function edit(){
        if(IS_POST){
            try{
                $data = $_POST;
                $result = UserHelper::edit($data);
                if($result){
                    $role_user_model=M("Role_user_rel");
                    $role_user_model->where(array("UserID"=>$data['ID']))->delete();
                    if(!empty($_POST['RoleID']) && is_array($_POST['RoleID'])){
                        $RoleIDs = I('post.RoleID/a');
                        foreach ($RoleIDs as $role_id){
                            $role_user_model->add(array("RoleID"=>$role_id,"UserID"=>$data['ID']));
                        }
                    }
                    if(!empty($_POST['ApplyUserID'])){
                        $departments = I('ApplyUserID');
                        $departmentList = explode(',',$departments);
                        foreach($departmentList as $item){
                            $UserDepData['UserID'] = $result;
                            $UserDepData['DepID'] =  $item;
                            $rel = M('User_dep_rel')->where($UserDepData)->find();
                            if(!$rel){
                                M('User_dep_rel')->add($UserDepData);
                            }
                        }
                    }
                    $this->success('编辑成功！');
                }else{
                    $this->error('编辑失败！');
                }
            }catch(Exception $exception){
                $this->error($exception->getMessage());
            }
        }else{
            $id = I('id');
            $user = M('User')->find($id);
            $where['IsDel'] = array('neq','1');
            $Roles = M('Role')->where($where)->order('ID desc')->select();
            $RoleIDs=M('Role_user_rel')->where(array("UserID"=>$id))->getField("RoleID",true);
            $departments = M('Department as d')->join('left join user_dep_rel as rel on rel.DepID=d.ID')
                ->where(array('rel.UserID' => $id))->field('d.*')->select();
            //循环遍历部门，获取ids和names
            $departmentIdArray = [];
            $departmentNameArray = [];
            foreach($departments as $department){
                $departmentIdArray[] = $department['ID'];
                $departmentNameArray[] = $department['Name'];
            }
            $this->assign("RoleIDs",$RoleIDs);
            $this->assign('Roles',$Roles);
            $this->assign('DepIds',implode(',',$departmentIdArray));
            $this->assign('DepNames',implode(',',$departmentNameArray));
            $this->assign('user',$user);
            $this->assign('Sex',$this->Sex);
            $this->display();
        }
    }

    public function delete(){
        $id = I('id');
        try{
            UserHelper::delete($id);
            $this->success('删除成功！');
        } catch (UserInfoException $exception){
            $this->error($exception->getMessage());
        }
    }
}